"""
Case Type   : cm
Case Name   : cm_ctl query参数-g/--minorityAz/-z合理验证
Create At   : 2024-07
Owner       : haomeng
Description :
    1、查看集群状态
    2、显示备份和恢复集群信息
    3、查询指定Az的cms
    4、查询数据库所有实例Az名称，不指定-c
    5、查询数据库所有实例Az名称，不指定-c，-v
Expect      :
    1、集群所有节点状态正常，显示Normal
    2、查询成功
    3、查询成功
    4、查询成功
    5、查询成功
History     :
"""

import os
import re
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node

Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != Primary_SH.get_node_num(), '需1主2备环境，否则不执行')
class CmCtl(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.comsh = CommonSH('PrimaryDbUser')
        self.pri_user = Node('PrimaryDbUser')
        self.constant = Constant()

    def test_cm(self):
        text = '----step1:查看集群状态; expect:集群状态正常,DN主在节点1----'
        self.log.info(text)

        status = self.comsh.exec_cm_ctl('query', '-Cv')
        self.log.info(status)
        self.assertIn("cluster_state   : Normal", status)

        text = '----step2:显示备份和恢复集群信息; expect:查询成功----'
        self.log.info(text)

        query_list1 = []
        query1 = self.comsh.exec_cm_ctl('query', '-g')
        self.log.info(query1)
        for query in query1.splitlines():
            query_list1.append(query)
        self.log.info(query_list1)
        self.assertEqual(3, int(query_list1.count('instance_type: Datanode')), '检查失败')

        text = '----step3:查询指定Az的cms; expect:查询成功----'
        self.log.info(text)

        query2 = self.comsh.exec_cm_ctl('query', '--minorityAz=AZ1')
        self.log.info(query2)
        self.assertIn('Normal', query2.splitlines()[2], '检查失败')

        text = '------step4:查询数据库所有实例Az名称，不指定-c; expect:查询成功------'
        self.log.info(text)

        query_list3 = []
        query3 = self.comsh.exec_cm_ctl('query', '-v', '-z ALL')
        self.log.info(query3)
        for query in query3.splitlines():
            query_list3.append(query)
        self.log.info(query_list3)
        self.assertTrue(re.match('node.*',query_list3[9]), '检查失败')
        self.assertTrue(re.match('node.*',query_list3[-6]), '检查失败')

        text = '-----step5:查询数据库所有实例Az名称，不指定-c，-v  expect:查询成功-----'
        self.log.info(text)

        query4 = self.comsh.exec_cm_ctl('query', '-z ALL')
        self.log.info(query4)
        self.assertIn('Normal', query4.splitlines()[2], '检查失败')

    def tearDown(self):
        self.log.info('-----No need to clean-----')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
